package com.pn.service.impl;

import com.pn.entity.Result;
import com.pn.entity.User;
import com.pn.mapper.UserMapper;
import com.pn.page.Page;
import com.pn.service.UserService;
import com.pn.utils.DigestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImp implements UserService {

    //注入UserMapper
    @Autowired
    private UserMapper userMapper;

    //根据用户名查找用户的业务方法
    @Override
    public User findUserByCode(String userCode) {
        return userMapper.findUserByCode(userCode);
    }

    /**
     * 分页查询用户的业务方法
     *
     * @param page
     * @param user
     * @return
     */
    @Override
    public Page queryUserPage(Page page, User user) {
        int userCount = userMapper.selectUserCount(user);
        List<User> userList = userMapper.selectUserPage(page, user);
        page.setTotalNum(userCount);
        page.setResultList(userList);
        return page;
    }

    @Override
    public Result saveUser(User user) {
//        用户名查重
        User oldUser = userMapper.findUserByCode(user.getUserCode());
        if (oldUser != null) {
            return Result.err(Result.CODE_ERR_BUSINESS, "用户名已存在");
        }
        String userPwd = DigestUtil.hmacSign(user.getUserPwd());
        user.setUserPwd(userPwd);
        userMapper.insertUser(user);
        return Result.ok("添加用户成功");
    }

    /**
     * @param user
     * @return
     */
    @Override
    public Result updateUserState(User user) {
        //根据用户id修改用户状态
        int i = userMapper.updateUserState(user);
        if (i > 0) {
            return Result.ok("修改成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "修改失败！");
    }

    /**
     * @param userId
     * @return
     */
    @Override
    public int deleteUserById(Integer userId) {
        return userMapper.setUserDelete(userId);
    }

    @Override
    public Result updateUserName(User user) {

        int i = userMapper.updateNameById(user);
        if (i > 0) {
            return Result.ok("用户修改成功");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "用户昵称修改失败");
    }

    /**
     * 重置密码的业务
     *
     * @param userId
     * @return
     */
    @Override
    public Result resetPwd(Integer userId) {
        User user = new User();
        user.setUserId(userId);
        user.setUserPwd(DigestUtil.hmacSign("123456"));
//        格局用户id修改密码
        int i = userMapper.updatePwdById(user);
        if (i > 0) {
            return Result.ok("密码重置成功");
        }
//        密码修改失败
        return Result.err(Result.CODE_ERR_BUSINESS, "用户重置失败");
    }
}
